package com.yusp75.myexam

import android.app.Application
import android.util.Log
import com.google.android.gms.ads.MobileAds
import com.kc.openset.config.OSETSDK
import com.kc.openset.listener.OSETInitListener
import com.yusp75.myexam.ad.OpenAdManager
import com.yusp75.myexam.di.appModule
import com.yusp75.myexam.di.repositoryModule
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.GlobalContext.startKoin

class MyApp : Application() {

    private val adScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private val initializationLock = Mutex()
    private var isAdReady = false

    val openAdManager: OpenAdManager by lazy {
        MobileAds.initialize(this)
        OpenAdManager(this).also {
            adScope.launch {
                initializationLock.withLock {
                    try {
                        it.preloadAd()
                        isAdReady = true
                    } catch (e: Exception) {
                        Log.e("AdInit", "预加载失败", e)
                    }
                }
            }
        }
    }

    override fun onCreate() {
        super.onCreate()

        // 注入
        startKoin {
            androidContext(this@MyApp)
            modules(appModule) // 实际调用点
            modules(repositoryModule)
        }

        initAdSet()
    }

    suspend fun awaitAdInitialization() {
        if (!isAdReady) {
            initializationLock.withLock {
                if (!isAdReady) {
                    openAdManager // 触发初始化
                }
            }
        }
    }

    override fun onTerminate() {
        super.onTerminate()
        adScope.cancel()
    }

    private fun initAdSet() {
        //OSETSDK.getInstance().setUserId("201819")
        OSETSDK.getInstance().init(this, "56DFBF6C8382940D", object : OSETInitListener {
            override fun onError(s: String) {
                // 初始化失败：会调用不到广告，请选择合适的时机重新进行初始化
                Log.e("广告初始化", s)
            }

            override fun onSuccess() {
                // 初始化成功：可以开始调用广告
                Log.e("广告初始化", "成功")
            }
        })

    }

    //
}
